import RecruitAPI from '../../../common/api/lookrecruit/recruit.api.js';
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";

(function (window, document, $) {
    let _vm
    let _page = {
        pageSize: 10,
        pageIndex: 0,
        totalPages: -1,
    }
    $(function () {
        _vm = new Vue({
            el: "#lookrecruit",
            data() {
                return {
                    page: { ..._page },
                    entries: [],
                    statusdata: []
                }
            }
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        _initSlide()
        _initCommand()
        pullLoad()
        _initOpera()
    });
    // 初始化操作
    const _initCommand = async () => {
        requestDict(DictionaryType.DELIERY_TYPE).then(res => {
            res.data.forEach(item => {
                item.displayName == "合格" ? item.stadata = 'hgst' : item.displayName == "不合格" ? item.stadata = 'unqualifiedst' : item.displayName == "待定" ? item.stadata = 'pendingst' : ""
            })
            _vm.statusdata = [...res.data]

        })
        let userInfo = await RecruitAPI.getLoginUserToStaff()
        let aslistdata = {
            "emplId": userInfo.id,
            "jobCVIds": [],
            "searchInfo": "",
        }
        let _data = _vm.page;
        RecruitAPI.jobAslist(Object.assign(aslistdata, _data)).then(res => {
            _page = {
                pageSize: 10,
                pageIndex: _data.pageIndex + 1,
                totalPages: res.totalPages
            }
            _vm._data.page = Object.assign({}, _page);
            // 简历状态
            res.items.forEach(element => {
                let statusArr
                // 有评估信息
                if (Utils.IsNotNull(element.assessRecords)) {
                    let curUserId = JSON.parse(Utils.GetSessionStorage('SNLoginUserInfo')).curUserId
                    // 判断评估消息是否有自己的
                    let creatorArr = element.assessRecords.filter(item => {
                        return item.creatorId == curUserId
                    })
                    //有自己的评估消息
                    if (Utils.IsNotNull(creatorArr)) {
                        let statusdataArr = [..._vm.statusdata]
                        let statusInfo = statusdataArr.filter(item => {
                            return item.value == creatorArr[0].status
                        })
                        // 评估信息中的状态 数据字典中 存在
                        if (Utils.IsNotNull(statusInfo)) {
                            statusArr = statusInfo[0]
                        }
                    }
                }
                let max = 0
                let minwork = new Date().getTime()
                let eduredegree, rcworkExps
                // 教育经历
                let edudegree = [...element.cvSnapshot.educationExps]
                for (let i = 0; i < edudegree.length; i++) {
                    if (new Date(edudegree[i].endDate).getTime() > max) {
                        max = new Date(edudegree[i].endDate).getTime()
                        eduredegree = edudegree[i]
                    }
                }
                // 工作经历
                let recriutworkExps = [...element.cvSnapshot.workExps]
                let sjworkExps = "无工作经验"
                let addSum = 0
                if (Utils.IsNotNull(recriutworkExps)) {
                    for (let i = 0; i < recriutworkExps.length; i++) {
                        // if (new Date(recriutworkExps[i].startDate).getTime() < minwork) {
                        //     minwork = new Date(recriutworkExps[i].startDate).getTime()
                        //     rcworkExps = recriutworkExps[i]
                        // }
                        let addDifference = ((new Date(recriutworkExps[i].endDate).getTime() - new Date(recriutworkExps[i].startDate).getTime()) / 31536000000)
                        addSum = Number(addSum) + Number(addDifference)
                    }
                    addSum = addSum.toFixed(1)
                    if (addSum < 1) {
                        sjworkExps = "1年以下工作经验"
                    }
                    else {
                        sjworkExps = `${addSum}年工作经验`
                    }
                    // sjworkExps = ((new Date().getTime() - new Date(rcworkExps.startDate).getTime()) / 31536000000).toFixed(1)
                    // if (sjworkExps < 1) {
                    //     sjworkExps = "1年以下工作经验"
                    // }
                    // else {
                    //     sjworkExps = `${sjworkExps}年工作经验`
                    // }
                }
                if (Utils.IsNotNull(element.cvSnapshot.assessRecords)) {
                    let curUserId = JSON.parse(Utils.GetSessionStorage('SNLoginUserInfo')).curUserId
                    let creatorArr = element.cvSnapshot.assessRecords.filter(item => {
                        return item.creatorId == curUserId
                    })
                    if (Utils.IsNotNull(creatorArr)) {
                        let statusdataArr = [..._vm.statusdata]
                        let statusInfo = statusdataArr.filter(item => {
                            return item.value == creatorArr[0].status
                        })
                        if (Utils.IsNotNull(statusInfo)) {
                            $('#restatus').css('display', 'block')
                            statusInfo[0].displayName == "合格" ? $('#pdstatus').addClass('hg') : statusInfo[0].displayName == "不合格" ? $('#pdstatus').addClass('unqualified') : statusInfo[0].displayName == "待定" ? $('#pdstatus').addClass('pending') : ""
                            _vm.statusInfo = {
                                ...statusInfo[0]
                            }
                        }
                    }
                }
                let recruitData = {
                    "id": element.id,
                    "rename": element.cvSnapshot.name,
                    "regender": element.cvSnapshot.gender == 1 ? "先生" : "女士",
                    "rejobPostName": element.jobPostName,
                    "reage": Utils.IsNotNull(element.cvSnapshot.age) ? element.cvSnapshot.age + '岁 |' : "",
                    "reworkExps": sjworkExps + ' |',
                    "redegree": eduredegree.degree,
                    "reprofession": Utils.IsNotNull(eduredegree.profession) ? ' | ' + eduredegree.profession : "",
                    "statusName": statusArr?.displayName,
                    "status": statusArr?.stadata,

                }
                _vm.entries.push(recruitData)
            });
        })

    }
    const _initOpera = () => {
        $(document).on('click', '.recruit-contents-item-box', function (e) {
            let index = $(this).index()
            let redetailid = _vm.entries[index].id
            location.href = `../lookrecruit/recruitdetails.html?v=${Utils.GetTime()}&id=${redetailid}&entertype=1`;
        })

    }
    // 初始化页码
    const _initPage = () => {
        _page = {
            pageSize: 10,
            pageIndex: 0,
            totalPages: -1,
        }
        _vm._data.page = Object.assign({}, _page);
    }
    // 下拉加载
    const _initSlide = () => {
        //分别设置滑动距离，开始位置，结束位置，和模拟数据的定时器
        let disY, startY, endY, timer, t, pullheight;

        // 触摸开始
        $('#lookrecruitmain').on('touchstart', function (e) {
            startY = e.originalEvent.changedTouches[0].pageY;//开始时的坐标
        });
        // 移动中
        $('#lookrecruitmain').on('touchmove', function (e) {

            endY = e.originalEvent.changedTouches[0].pageY;
            disY = endY - startY;//移动后的坐标减去开始坐标，滑动距离。
            if (isTop() && disY > 0) {
                e.preventDefault();
            }
            if (disY < 60) {
                $('#pull-down').css({
                    height: disY + 'px'//父盒子的高度随着滑动距离变化，有最大值。
                });
            }
            else {
                $('#pull-down').css({
                    height: 60 + 'px'//父盒子的最大高度
                });
            }
            // 结束时
            $('#lookrecruitmain').on('touchend', function (e) {
                clearInterval(timer);
                endY = e.originalEvent.changedTouches[0].pageY;
                disY = endY - startY;
                if (isTop() && disY > 0) {
                    timer = setInterval(function () {
                        $('#pull-down').css({
                            height: 0 + 'px',//松手后的返回。
                        });
                        clearInterval(timer);
                        _initPage()
                        _vm.entries = []
                        _initCommand();//加载数据 
                    }, 300)
                } else {
                    $('#pull-down').css({
                        height: 0 + 'px',//松手后的返回。
                    });
                }
            })
        });
    }
    const isTop = () => {
        var t = document.documentElement.scrollTop || document.body.scrollTop;
        return t === 0 ? true : false;
    }

    //TODO : 上拉加载
    const pullLoad = () => {
        // 监听滚动的父容器
        $("body").infinite().on("infinite", function () {
            let _data = _vm._data.page;
            if (_data.pageIndex == _data.totalPages) {
                return
            }
            let self = this;
            if (self.loading) return;
            self.loading = true;
            setTimeout(function () {
                _initCommand();
                self.loading = false;
            }, 500);   //模拟延迟
        });
    }

})(window, document, jQuery)

